/**
 * Copyright (c) 2017-2018, zengjintao (1913188966@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfast.framework.web.core.param;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfast.framework.web.core.RequestMethodMapping;

/**
 * MethodPara接口实例创建者
 * @author zengjintao
 * @version 1.0
 * @createTime 2018年1月6日下午9:16:40
 */
public class ParamProcessorBuilder {
	
	private static final ParamProcessorBuilder paramProcessorBuilder = new ParamProcessorBuilder();
	
	private ParamProcessorBuilder(){
		
	}
	
	public static final ParamProcessorBuilder getParaBuilder() {
		return paramProcessorBuilder;
	}
	
	public ParamProcessor builder(RequestMethodMapping requestMethodMapping, HttpServletRequest request, HttpServletResponse response) {
		ParamProcessor paramProcessor = new ParamProcessor();
		Method method = requestMethodMapping.getMethod();
		Parameter[] parameters = method.getParameters();
		for (Parameter parameter : parameters) {
			MethodParam methodPara = createMethodParam(requestMethodMapping, parameter, request, response);
			paramProcessor.addMethodParam(methodPara);
		}
		return paramProcessor;
	}

	@SuppressWarnings("rawtypes")
	private MethodParam createMethodParam(RequestMethodMapping requestMethodMapping, Parameter parameter, HttpServletRequest request,
			HttpServletResponse response) {
		Annotation[] annotations = parameter.getAnnotations();

		Class<?> classType = parameter.getType();//获取参数类型
		//优先处理注解
		if (annotations != null && annotations.length > 0) {
			return new AnnotationParam(requestMethodMapping, request, parameter.getName(), annotations[0], classType);
		} else if (classType.isAssignableFrom(HttpServletRequest.class)) {
			return new HttpServletRequestParam(request);
		} else if (classType.isAssignableFrom(HttpServletResponse.class)) {
			return new HttpServletResponseParam(response);
		} else if (classType.isAssignableFrom(Map.class)) {
			return new MapParam(request);
		}
		return new BeanParam(request, classType);
	}
}
